package com.atcx.interceptor;

import com.atcx.util.Constants;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Copyright (C), 2017-2022, MIDOU
 * ClassName: MinorInterceptor
 * Author:   pangshu
 * Date:     2022/7/20 18:29
 * Version: 1.0
 * Description:
 */
@Component
public class MinorInterceptor implements HandlerInterceptor {
    private Long currentTime = 0L;
    private Long beginTime = 0L;
    private Long executeTime = 0L;
    private Long responseTime = 0L;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        beginTime = System.currentTimeMillis();
        HttpSession session = request.getSession();
        Object attribute = session.getAttribute(Constants.CURRENT_USER);
        if (attribute==null){
            response.sendRedirect(request.getContextPath()+"/index.jsp");
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        executeTime = System.currentTimeMillis() - beginTime;
        System.out.println(request.getRequestURI()+"的执行时间为："+executeTime+"毫秒");
        currentTime = System.currentTimeMillis();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        responseTime = System.currentTimeMillis() - currentTime;
        System.out.println(request.getRequestURI()+
                "的响应时间为："+responseTime+"毫秒");
    }
}
